//
//  DataLoader.swift
//  icloud
//
//  Created by raymond on 2022/5/20.
//

import Foundation
import Combine
import SwiftUI

class DataSource: ObservableObject {
  @Published var model: Response<TSysUser> = load("resp_users.json")
  
  func sortedUsers()->Binding<[TSysUser]> {
    Binding<[TSysUser]> (
      get: {
        self.model.result.sorted{$0.id<$1.id}
      },
      set: { result in
        for user in result {
          if let index = result.firstIndex(where: {$0.id == user.id}){
            self.model.result[index] = user
          }
        }
      }
    )
  }
}

func load<T: Decodable>(_ filename: String) -> T {
  let data: Data
  
  guard let file = Bundle.main.url(forResource: filename, withExtension: nil)
  else {
    fatalError("Couldn't find \(filename) in main bundle.")
  }
  
  do {
    data = try Data(contentsOf: file)
  } catch {
    fatalError("Couldn't load \(filename) from main bundle:\n\(error)")
  }
  
  do {
    let decoder = JSONDecoder()
    return try decoder.decode(T.self, from: data)
  } catch {
    fatalError("Couldn't parse \(filename) as \(T.self):\n\(error)")
  }
}
